<?php

namespace Dcat\Admin\ApiTester\Http\Controllers;

use Dcat\Admin\Admin;
use Dcat\Admin\ApiTester\Actions\Tree\EditApiInfo;
use Dcat\Admin\ApiTester\Models\ApiTester;
use Dcat\Admin\ApiTester\Models\CgkjProj;
use Dcat\Admin\Form;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Show;
use Dcat\Admin\Tree;
use Dcat\Admin\Widgets\Card;
use Dcat\Admin\Widgets\Form as WidgetsForm;
use Dcat\Admin\Widgets\Modal;
use Dcat\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ApiTesterController extends AdminController {

    const Stage_arr = [
        'none' => '不显示',
        'deving' => '开发中',
      'finish' => '已完成'
    ];
    public $proj_id;
    public $proj_code;
    public $projinfo;


    // 加载modal 和 js
    public function loadingtpl() {
        /*导入响应json数据*/
        Admin::html(
            <<<HTML
<div class="modal fade" id="exampleModal123" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">通过json方式导入</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="message-text" class="col-form-label">填写响应json (必须是正确的json数据格式)</label>
            <textarea rows="10" class="form-control" id="json-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="json-save">导入</button>
      </div>
    </div>
  </div>
</div>
HTML

        );

        Admin::html(
            '<div class="modal fade" id="add-api-group" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">添加接口分组</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form class="" method="post"  id="add-api-group-form" action="/admin/ycookies/api-tester/addgroup">
        <input type="hidden" name="proj_id" id="proj_id" value="' . $this->proj_id . '">
          <div class="form-group">
            <label for="recipient-name" class="col-form-label">分组名称:</label>
            <input type="text" name="group_name" class="form-control" id="group_name">
            <input type="hidden" name="is_group" class="form-control" value="1">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="add-api-group-save">添加</button>
      </div>
    </div>
  </div>
</div>');

        Admin::script(
            <<<JS
(function () {
    function gettrhtml(index,field_name){
        var htmls = `<tr class="has-many-table-resp_param-form fields-group" data-select2-id="select2-data-58-tujk"><td><div class="form-group row form-field">

            <div class="col-md-0 text-capitalize asterisk hidden control-label">
                <span>字段名</span>
            </div>

            <div class="col-md-12 ">

                <div class="help-block with-errors"></div>
                <div class="input-group">

                    <input build-ignore="1" required="1" type="text" name="resp_param[new_`+ index +`][field_name]" value="`+ field_name +`" class="form-control field_resp_param_new_1 field_field_name_new_1 field_field_name" placeholder="输入 字段名"></div>


            </div>
        </div></td>


    <td data-select2-id="select2-data-57-00ue"><div class="form-group row form-field" data-select2-id="select2-data-56-napx">

            <div class="col-md-0 text-capitalize asterisk hidden control-label">
                <span>数据类型</span>
            </div>

            <div class="col-md-12 " data-select2-id="select2-data-55-hjg5">
                <div class="help-block with-errors"></div>
                <select class="form-control field_resp_param_new_`+ index +` field_field_type_new_`+ index +` field_field_type select2-hidden-accessible" style="width: 100%;" name="resp_param[new_`+ index +`][field_type]" build-ignore="1" data-value="" initialized="1" id="_1017347199a89347" data-select2-id="select2-data-_1017347199a89347" tabindex="-1" aria-hidden="true">
                <option value="" data-select2-id="select2-data-13-zvlw"></option>
                <option value="string" data-select2-id="select2-data-74-czg6" selected>string</option>
                <option value="integer" data-select2-id="select2-data-75-q9r2">integer</option>
                <option value="number" data-select2-id="select2-data-76-k9it">number</option>
                <option value="boolean" data-select2-id="select2-data-77-inka">boolean</option>
                </select>
                <span class="select2 select2-container select2-container--default select2-container--below" dir="ltr" data-select2-id="select2-data-12-ap8o" style="width: 100%;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-disabled="false" aria-labelledby="select2-_1017347199a89347-container"><button type="button" class="select2-selection__clear" tabindex="-1" title="删除所有项目" aria-label="删除所有项目" aria-describedby="select2-_1017347199a89347-container" data-select2-id="select2-data-78-qhan"><span aria-hidden="true">×</span></button><span class="select2-selection__rendered" id="select2-_1017347199a89347-container" role="textbox" aria-readonly="true" title="string">string</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span></div>
        </div></td>


    <td><div class="form-group row form-field">

            <div class="col-md-0 text-capitalize hidden control-label">
                <span>字段说明</span>
            </div>

            <div class="col-md-12 ">

                <div class="help-block with-errors"></div>
                <div class="input-group">

                    <input build-ignore="1" type="text" name="resp_param[new_`+ index +`][field_desc]" value="" class="form-control field_resp_param_new_1 field_field_desc_new_1 field_field_desc" placeholder="输入 字段说明"></div>


            </div>
        </div></td>


    <td class="hidden"><input type="hidden" name="resp_param[new_`+ index +`][_remove_]" value="0" class="field_resp_param_new_1 field__remove__new_1 field__remove_ form-removed field_resp_param_new_1___remove__ _normal_" build-ignore="1"></td>

    <td class="form-group">
        <div>
            <div class="remove btn btn-white btn-sm pull-right"><i class="feather icon-trash"></i></div>
        </div>
    </td>
</tr>`;
        return htmls;
    }
    
    $('#json-save').on('click',function(e) {
      Dcat.success('完成导入');
      var json_text = $('#json-text').val();
      var name = 'booking123';
      json_text = JSON.parse(json_text);
      var num = 1;
      $.each(json_text, function (index, value) {
          var trhtml = gettrhtml(num,index);
          $('.has-many-table-resp_param-forms').append(trhtml);
          num++;
		});
      $('#exampleModal123').modal('hide');
    });
    $('#add-api-group-save').on('click',function(e) {
        var formdata = $('#add-api-group-form');
      Dcat.Form({
        form: formdata,
        success: function (res) {
            if (res.status != 'success') {
                Dcat.error(res.msg);
                return false;
            }
            $('#add-api-group').modal('hide');
            Dcat.success('添加成功');
            Dcat.reload();
            return false;
        },
        error: function () {
        }
    });
      
    });
})()    
JS
        );
    }

    /**
     * @desc index page
     * @param Content $content
     * @return Content
     * author eRic
     * dateTime 2022-12-31 17:35
     */
    public function index(Content $content) {
        $this->proj_id   = Request()->get('proj_id');
        $projinfo = CgkjProj::where('id', $this->proj_id)->first();
        $this->projinfo  = $projinfo;
        $this->proj_code = $projinfo->code;
        $this->loadingtpl();
        // 行里面有多个列,列里面再嵌套行
        $content->row(function (Row $row) {
            $row->column(4, function (Column $column) {
                //$column->row(Runapidoc::make()->render());
                //$modal = Modal::make()->title('');
                Form::dialog('项目信息')
                    ->click('.api-obj-form') // 绑定点击按钮
                    ->url('ycookies/proj/'.$this->proj_id.'/edit') // 表单页面链接，此参数会被按钮中的 “data-url” 属性替换。。
                    ->width('80%') // 指定弹窗宽度，可填写百分比，默认 720px
                    ->height('650px') // 指定弹窗高度，可填写百分比，默认 690px
                    ->success('Dcat.reload()'); // 新增成功后刷新页面

                Form::dialog('公共参数管理')
                    ->click('.common-parem-form') // 绑定点击按钮
                    ->url('ycookies/proj/'.$this->proj_id.'/edit?type=common_param') // 表单页面链接，此参数会被按钮中的 “data-url” 属性替换。。
                    ->width('80%') // 指定弹窗宽度，可填写百分比，默认 720px
                    ->height('650px') // 指定弹窗高度，可填写百分比，默认 690px
                    ->success('Dcat.reload()'); // 新增成功后刷新页面

                Form::dialog('header 参数管理')
                    ->click('.header-parem-form') // 绑定点击按钮
                    ->url('ycookies/proj/'.$this->proj_id.'/edit?type=header_param') // 表单页面链接，此参数会被按钮中的 “data-url” 属性替换。。
                    ->width('80%') // 指定弹窗宽度，可填写百分比，默认 720px
                    ->height('650px') // 指定弹窗高度，可填写百分比，默认 690px
                    ->success('Dcat.reload()'); // 新增成功后刷新页面

                $column->append(function () {
                    //$editPage2 = admin_base_path('ycookies/proj/'.$this->proj_id.'/edit?type=header_param');
                    //$editPage1 = admin_base_path('ycookies/proj/'.$this->proj_id.'/edit?type=common_param');
                    $htmls = "<div class=\"btn-group pull-right\" style=\"margin-bottom: 5px;\">";
                    $htmls .= "<a  class=\"btn btn-sm btn-success api-obj-form \" href=\"#\"><i class=\"fa fa-book\"></i> &nbsp;项目信息</a>";
                    $htmls .= "<span class='btn btn-sm btn-success header-parem-form' ><i class=\"fa fa-edit\"></i> &nbsp; header参数</span>";
                    $htmls .= "<span class='btn btn-sm btn-success common-parem-form' ><i class=\"fa fa-edit\"></i> &nbsp;公共参数</span>";
                    $htmls .= "</div>";
                    //$htmls = '<div class="pull-left" style="font-size: 22px"></div><div class="btn-group pull-right" style="margin-bottom: 5px;"><a  class="btn btn-sm btn-success" href="#"><i class="fa fa-book"></i> &nbsp;项目信息</a> <a  class="btn btn-sm btn-success" href="#"><i class="fa fa-edit"></i> &nbsp;header</a><a  class="btn btn-sm btn-success" href="#"><i class="fa fa-edit"></i> &nbsp;公共参数</a></div>';
                    return $htmls;
                });
            });
            $row->column(8, function (Column $column) {

                $column->append(function () {
                    $urls = url('/admin/ycookies/api-tester/proj/apidoc') . '?docId=' . $this->proj_code;
                    return '<div class="pull-left" style="font-size: 22px">'.$this->projinfo->name.'</div><div class="btn-group pull-right" style="margin-bottom: 5px;"><a  class="btn btn-orange" href="/admin/ycookies/api-tester?proj_id='.$this->projinfo->id.'"><i class="fa fa-plus-circle"></i>新建接口</a>
                ' . $this->modal1($this->proj_id) . '
                <a  class="btn btn-success" target="_blank" href="' . $urls . '"><i class="feather icon-eye"></i> 查看文档</a>
</div>';
                });
                //$column->row();
            });
        });
        //$content->row('<br>');
        $content->row(function (Row $row) {
            $row->column(4, function (Column $column) {
                $tab  = new Tab();
                $type = request('_t', 1);
                $tab->add('接口列表', $this->treeView()->render());
                //$tab->add('历史', '');

                $card = Card::make('项目接口列表', $tab);
                $column->row($card);
                $column->row('<br>');

                $column->row(Card::make('作者展示', Admin::view('ycookies.api-tester::author')));
            });
            $row->column(8, function (Column $column) {
                if (Request()->has('id')) {
                    $id    = Request()->get('id');
                    $infos = ApiTester::find($id);
                    if ($infos) {
                        $form = new WidgetsForm($infos->toArray());
                    } else {
                        $form = new WidgetsForm();
                    }
                } else {
                    $form = new WidgetsForm();
                }


                $form->setFormId('api-tester-add-form');
                $form->action(admin_url('ycookies/api-tester/handle')); // $menuModel::selectOptions()
                $form->row(function (Form\Row $form) {
                    $form->width(3)->select('parent_id', '分组 <a href="#" class="add-api-group" data-toggle="modal" data-target="#add-api-group" style="font-size: 12px;float:right;"> 添加分组</a>')->placeholder('请选择')->options(ApiTester::getParentInfo());
                    $form->width(5)->text('title', '接口名称')->required();
                    $form->width(3)->select('stage', '开发阶段')->options(self::Stage_arr)->default('none');
                    $form->hidden('proj_id')->value(Request()->get('proj_id'));
                });
                $form->row(function (Form\Row $form) {
                    $form->width(3)->select('method', '请求方式')->options(ApiTester::$methods)->required();
                    $form->width(6)->text('uri', '接口地址')->required('uri');
                    $form->width(3)->radio('is_common', '公共参数支持')->options(['0'=> '否','1'=> '是'])->default(0);
                });
                $form->row(function (Form\Row $form) {
                    $form->textarea('descs', '接口描述')->value('暂无');
                    $form->table('api_param', '请求参数', function (NestedForm $table) {
                        $table->text('field_name', '字段名')->prepend('')->required();
                        $table->select('field_type', '数据类型')->options(['string' => 'string', 'integer' => 'integer', 'number' => 'number', 'boolean' => 'boolean', 'file' => 'file'])->required();
                        $table->radio('field_required', '是否必值')->options(['Y' => '是', 'N' => '否'])->required();
                        $table->text('field_default', '默认值')->prepend('');
                        $table->text('field_value', '测试值')->prepend('');
                        $table->text('field_desc', '字段描述')->prepend('');
                    });
                });
                $form->row(function (Form\Row $form) {
                    $form->html('<button type="button" data-toggle="modal" data-target="#exampleModal123"  class="btn btn-info"><i class="feather icon-save"></i>通过json方式导入</button>');
                    $form->table('resp_param', '响应参数', function (NestedForm $table) {
                        $table->text('field_name', '字段名')->prepend('')->required();
                        $table->select('field_type', '数据类型')->options(['string' => 'string', 'integer' => 'integer', 'number' => 'number', 'boolean' => 'boolean'])->default('string');
                        $table->text('field_desc', '字段说明')->prepend('');
                    });
                });


                $form->disableResetButton();
                $form->width(9, 2);

                // 接口信息表单
                $column->append(Card::make('接口信息', $form));

                /* 响应信息面板 */
                $column->append($this->respinfo());
            });

        });
        $content->row('<br>');

        $this->loadScript();
        // 引入静态资源
        Admin::requireAssets('@ycookies.api-tester');

        // 返回视图
        return $content
            ->title('接口文档')
            ->breadcrumb(['text' => '接口文档', 'url' => ''])
            ->description('可管理接口并做测试');
    }

    protected function loadScript() {
        $urls = url('/admin/ycookies/api-tester/proj/apidoc') . '?docId=' . $this->proj_code;
        Admin::script(
            <<<JS
    $('.eye-apidoc').on('click',function(e) {
      window.location.href = '{$urls}'
    })
JS
        );
    }

    /**
     * @desc 生成文档
     * @return Modal
     * author eRic
     * dateTime 2022-12-31 20:35
     */
    protected function modal1($proj_id) {

        $form = new WidgetsForm();
        $form->action(admin_url('ycookies/api-tester/run'));
        $form->hidden('proj_id', '')->value($proj_id);
        $form->disableResetButton();// 禁止重置按键
        return Modal::make()
            ->id('run-apidoc')
            ->title('生成文档')
            ->body($form)
            ->button('<button type="button" class="btn btn-info"><i class="feather icon-box"></i> 生成文档</button>');
    }

    /**
     * @desc 生成文档
     * author eRic
     * dateTime 2022-12-31 20:22
     */
    public function run(Request $request) {
        $request->validate([
            'proj_id' => 'required|integer',
        ], [
            'proj_id.required' => '项目ID 不能为空',
        ]);

        $proj_id   = Request()->get('proj_id');
        $proj_info = CgkjProj::find($proj_id);
        $api_list  = ApiTester::where(['proj_id' => $proj_id, 'is_group' => 0])->orderBy('order','DESC')->get();
        $proj_code = $proj_info->code;

        $assetpath = public_path('vendor/dcat-admin-extensions/ycookies/api-tester/json/apidoc.json');
        $demojson  = file_get_contents($assetpath);
        $demojson  = json_decode($demojson, true);

        $demojson['info']['title']       = $proj_info->name;
        $demojson['info']['description'] = $proj_info->description;
        $demojson['host']                = $proj_info->host;
        $demojson['basePath']            = $proj_info->basePath;

        $group_list = ApiTester::where(['proj_id' => $proj_id, 'is_group' => 1])->orderBy('id', 'DESC')->get();

        // 生成 tags
        $demojson['tags']  = [];
        $demojson['paths'] = [];

        if ($group_list->isEmpty()) {
            $demojson['tags'][] = [
                'name'        => '全部',
                'description' => '',
                'sortWeight'  => 0
            ];
        } else {
            $tags = [];
            foreach ($group_list as $key => $items) {
                $tags[] = [
                    'name'        => $items->title,
                    'description' => '',
                    'sortWeight'  => $items->order,
                ];
            }

            $demojson['tags'] = $tags;
        }
        $demojson['paths'] = $this->handlePaths($api_list,$proj_id);
        $new_json_path     = public_path('vendor/dcat-admin-extensions/ycookies/api-tester/json/' . $proj_code . '.json');
        $json_centet       = json_encode($demojson, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        $json_centet       = str_replace('\/', '/', $json_centet);
        file_put_contents($new_json_path, $json_centet);

        return JsonResponse::make()->success('成功！' . $assetpath)->script(
            <<<JS
            $('#run-apidoc').modal('hide');
JS
        );
    }

    /**
     * @desc 处理接口参数
     * @param $list
     * author eRic
     * dateTime 2023-01-06 18:32
     */
    public function handlePaths($api_list,$proj_id) {
        $proj_info = CgkjProj::find($proj_id);
        $paths = [];
        if (!empty($api_list)) {
            foreach ($api_list as $key => $items) {
                $parameters = [];
                $api_param  = json_decode($items->api_param, true);
                $method     = strtolower($items->method);
                $ins        = 'formData';
                if ($method == 'get') {
                    $ins = 'query';
                }
                // 公共参数
                if($items->is_common == 1 && !empty($proj_info->common_param)){
                    foreach ($proj_info->common_param as $key0 => $field0) {
                        $required = false;
                        // 是否必填
                        if ($field0['field_required'] == 'Y') {
                            $required = true;
                        }
                        $parameters[] = [
                            'name'        => $field0['field_name'],
                            'in'          => $ins,
                            'description' => $field0['field_desc'],
                            'required'    => $required,
                            'type'        => $field0['field_type'],
                            'default'     => !empty($field0['field_default']) && $field0['field_default'] != null ? $field0['field_default'] : '',
                        ];
                    }
                }
                // 接口数据
                if (!empty($api_param)) {
                    foreach ($api_param as $key => $field) {
                        $required = false;
                        // 是否必填
                        if ($field['field_required'] == 'Y') {
                            $required = true;
                        }
                        $parameters[] = [
                            'name'        => $field['field_name'],
                            'in'          => $ins,
                            'description' => $field['field_desc'],
                            'required'    => $required,
                            'type'        => $field['field_type'],
                            'default'     => !empty($field['field_default']) && $field['field_default'] != null ? $field['field_default'] : '',
                        ];
                    }

                }
                // 响式数据
                $resp_param = json_decode($items->resp_param, true);
                $responses  = [];
                if (!empty($resp_param)) {
                    foreach ($resp_param as $key1 => $field1) {
                        $required1 = false;
                        // 是否必填
                        /*if($field1['field_required'] == 'Y'){
                            $required1 = true;
                        }*/
                        $responses[$field1['field_name']] = [
                            'description' => $field1['field_desc'],
                            'required'    => $required1,
                            //'format'=>
                            'type'        => $field1['field_type'],
                        ];
                    }

                }
                /**
                 * [type] => object
                 * [format] =>
                 * [description] => 默认响应
                 * [title] => default
                 * [properties] => Array
                 */
                $parent_name = '全部';
                if ($items->parent_id != 0) {
                    $parent_name = ApiTester::where(['id' => $items->parent_id])->value('title');
                }

                $paths[$items->uri] = [
                    $method => [
                        'tags'          => [$parent_name],
                        'summary'       => $items->title,
                        'description'   => $items->descs,
                        'schemes'       => ['http'],
                        'consumes'      => ['application/json'],
                        'produces'      => ['application/json'],
                        'parameters'    => $parameters,
                        'responses'     => [
                            '404'     => [],
                            'default' => [
                                'description' => '',
                                'schema'      => [
                                    'type'        => 'object',
                                    'format'      => '',
                                    'description' => '默认响应',
                                    'title'       => 'default',
                                    'properties'  => $responses,
                                ]
                            ]
                        ],
                        "devStatus"     => $items->stage,
                        "devStatusName" => $items->stage_txt,
                        "showDevStatus" => ( !empty($items->stage) && $items->stage != 'none') ? true :false,
                    ]
                ];
            }

        }
        return $paths;
    }

    /**
     * @desc 处理接口参数
     * @param $list
     * author eRic
     * dateTime 2023-01-06 18:32
     */
    public function handleApiParam($list) {

    }

    /**
     * @desc 处理接口响应数据
     * @param $list
     * author eRic
     * dateTime 2023-01-06 18:32
     */

    public function handleRespParam($list) {

    }


    /**
     * @desc 响应信息面板
     * @return Card
     * author eRic
     * dateTime 2022-12-24 14:12
     */
    public function respinfo() {
        $tab = new Tab();
        $tab->add('响应内容', '<pre class="line-numbers language-json"><code class="language-json"></code></pre>', true, 'tab-1');
        $tab->add('响应头', '<pre class="line-numbers language-json"><code class="language-json"></code></pre>', false, 'tab-2');
        $tab->add('cookies', '<pre class="line-numbers language-json"><code class="language-json"></code></pre>', false, 'tab-3');

        return Card::make('接口响应', $tab);
    }

    /**
     *  左则目录导航
     */
    protected function treeView() {

        return new Tree(ApiTester::class, function (Tree $tree) {
            $tree->query(function ($model) {
                $proj_id = Request()->get('proj_id');
                return $model->where('proj_id', $proj_id);
            });
            $tree->disableCreateButton();
            $tree->disableQuickCreateButton();
            $tree->disableEditButton();
            $tree->maxDepth(3);// 可以嵌套的层级 最多3级

            $tree->actions(function (Tree\Actions $actions) {
                //$actions->edit(false);
                $actions->prepend(new EditApiInfo());
                $actions->disableEdit();
                $actions->disableQuickEdit();
                //$actions->disableDelete();
            });

            $tree->branch(function ($branch) {
                $payload = "&nbsp;<strong>{$branch['title']}</strong>";

                if (!isset($branch['children'])) {
                    if (url()->isValidUrl($branch['uri'])) {
                        $uri = $branch['uri'];
                    } else {
                        $uri = $branch['uri'];
                    }
                    $yuanuri  = '/admin/ycookies/api-tester?proj_id='.$branch['proj_id'].'&id='.$branch['id'];
                    $uri     = Str::limit($uri, 10);
                    $payload .= "&nbsp;&nbsp;&nbsp;<a href=\"$yuanuri\" class=\"dd-nodrag\">$uri</a>";
                }

                return $payload;
            });
        });
    }


    /**
     * 接口信息提交处理
     * @desc
     * @param Request $request
     * @return JsonResponse
     * author eRic
     * dateTime 2022-12-24 14:15
     */
    public function handle(Request $request) {
        $request->validate([
            'proj_id' => 'required|integer',
            'title'   => 'required',
            'uri'     => 'required',
            'method'  => 'required',
            //'descs'  => 'required',
        ], [
            'proj_id.required'   => '项目ID 不能为空',
            'parent_id.required' => '父级 不能为空',
            'title.required'     => '接口名称 不能为空',
            'uri.required'       => '接口地址 不能为空',
            'method.required'    => '请求方法 不能为空',
            'descs'              => '接口描述 不能为空',
        ]);

        if (!empty($request->api_param)) {
            $request->validate([
                'api_param.*.field_name' => 'required_if:api_param.*._remove_,0',
                'api_param.*.field_type' => 'required_if:api_param.*._remove_,0',
            ], [
                'api_param.*.field_name.required_if' => '字段名 不能为空',
                'api_param.*.field_type.required_if' => '数据类型 不能为空',
            ]);
        }

        $all = $request->all();
        // 去除掉删除的
        $api_param = [];
        if (!empty($all['api_param'])) {
            foreach ($all['api_param'] as $key => $items) {
                if (!empty($items['_remove_']) && $items['_remove_'] == 1) {
                } else {
                    $api_param[$key] = $items;
                }
            }
        }
        //  去除掉删除的
        $resp_param = [];
        if (!empty($all['resp_param'])) {
            foreach ($all['resp_param'] as $key => $itemsk) {
                if (!empty($itemsk['_remove_']) && $itemsk['_remove_'] == 1) {
                } else {
                    $resp_param[$key] = $itemsk;
                }
            }
        }
        $uri = $all['uri'];
        if (substr($uri, 0, 1) != '/') {
            $uri = '/' . str_replace('\\', '', $uri);
        }
        $insdata = [
            'proj_id'    => $all['proj_id'],
            'title'      => $all['title'],
            'uri'        => $uri,
            'method'     => $all['method'],
            'descs'      => !empty($all['descs']) ? $all['descs'] : '',
            'parent_id'  => !empty($all['parent_id']) ? $all['parent_id'] : 0,
            'api_param'  => !empty($api_param) ? json_encode($api_param, JSON_UNESCAPED_UNICODE) : '',
            'resp_param' => !empty($resp_param) ? json_encode($resp_param, JSON_UNESCAPED_UNICODE) : '',
            'is_common' => !empty($all['is_common']) ? $all['is_common'] : '0',
        ];
        if(!empty($all['stage'])){
            $insdata['stage'] = $all['stage'];
            $insdata['stage_txt'] = self::Stage_arr[$all['stage']];
        }
        ApiTester::addOrUpdate(['proj_id' => $all['proj_id'], 'uri' => $request->uri, 'method' => $all['method']], $insdata);
        $method = $all['method'];
        $coll   = new  ApiTesterHandle();
        $uri    = $all['uri'];
        $user   = '';
        // 公共参数
        /*$api_param[] = [
            'field_name'  => 'api_token',
            'field_value' => 'eUTnFwZ97D2ms33JV2Vc265pNUwWG1Nd6gFEu2P2lodxdV7KMdcYxTaoRZJcX6sy'
        ];*/

        $projinfo    = CgkjProj::find($all['proj_id']);
        if(!empty($projinfo->common_param)){
            foreach ($projinfo->common_param as $key0 => $field0) {
                $api_param[] = [
                    'field_name'  => $field0['field_name'],
                    'field_value' => $field0['field_value']
                ];
            }
        }
        $parameters  = !empty($api_param) ? $api_param : [];
        $apiuris  = $projinfo->host . $projinfo->basePath . $uri;
        $response = $coll->call($method, $apiuris, $parameters, $user);

        /*'language'   => $lang,
            'status'     => [
            'code'  => $response->getStatusCode(),
            'text'  => $this->getStatusText($response),
        ],*/

        $datas    = $coll->parseResponse($response);
        $content  = $datas['content'];
        $header   = $datas['headers'];
        $cookies  = $datas['cookies'];
        $language = $datas['language'];

        return JsonResponse::make()->success('成功！')->script(
            <<<JS
            $('#tab_tab-1 pre code').html('');
            $('#tab_tab-2 pre code').html('');
            $('#tab_tab-3 pre code').html('');
            $('#tab_tab-1 pre code').html(`$content`);
            $('#tab_tab-2 pre code').html(`$header`);
            $('#tab_tab-3 pre code').html(`$cookies`);
            $('#tab_tab-1 pre code').removeClass(function (index, className) {
                return (className.match(/language-[^\s]+/) || []).join(' ');
            }).addClass('language-$language');
            Prism.highlightAll();
JS
        );

    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id) {
        return Show::make($id, new ApiTester(), function (Show $show) {
            $show->field('id');
            $show->field('parent_id');
            $show->field('order');
            $show->field('title');
            $show->field('uri');
            $show->field('method');
            $show->field('type');
            $show->field('descs');
            $show->field('head_param');
            $show->field('api_param');
            $show->field('resp_param');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form() {
        return Form::make(new ApiTester(), function (Form $form) {
            $form->display('id');
            $form->text('parent_id');
            $form->text('order');
            $form->text('title');
            $form->text('uri');
            $form->text('method');
            $form->text('type');
            $form->text('descs');
            $form->text('head_param');
            $form->text('api_param');
            $form->text('resp_param');
            $form->text('is_common');
            $form->display('created_at');
            $form->display('updated_at');
        });
    }

    // 添加分组
    public function addgroup(Request $request) {
        $request->validate([
            'proj_id'    => 'required|integer',
            'group_name' => 'required',
            'is_group'   => 'required',
        ], [
            'proj_id.required'    => '项目ID 不能为空',
            'proj_id.integer'     => '项目ID 只能是数字',
            'group_name.required' => '分组不能为空',
            'is_group.required'   => 'is_group 不能为空',
        ]);

        $insdata = [
            'proj_id'   => $request->proj_id,
            'title'     => $request->group_name,
            'is_group'  => 1,
            'uri'       => '/',
            'method'    => 'get',
            'descs'     => '',
            'parent_id' => 0,
        ];

        $model = ApiTester::create($insdata);
        $resq  = [
            'code'   => 200,
            'status' => 'success',
            'msg'    => '',
            'data'   => [],
        ];
        return Response()->json($resq);
    }
}